"""
Namespaced based caching for django.

You may have multiple cache items that need to be flushed when one object changes.
Without namespaces, you are forced to keep track of each key and flush them all manually.
If you put them in a namespace, then you can just flush the namespace and all keys contained 
within will get flushed as well.
"""

from django.core.cache import cache
import random
import string

def ns_key(namespace, key):
    """Generates a key based on the namespace and key arguments given.

    Arguments:
      namespace -- an arbitrary string that denotes the namespace.
      key -- a string appended to the namespace to generate a unique key.

    If either argument is passed as a list, a string will be generated by concatenting
    all items in the list.
    """
    if not isinstance(namespace, (unicode, str)):
        namespace = '_'.join(str(a) for a in namespace)
    if not isinstance(key, (unicode, str)):
        key = '_'.join(str(a) for a in key)
    key_prefix = cache.get("__namespace_%s__" % (namespace,))
    if key_prefix is None:
        key_prefix = ''.join( random.choice(string.letters) for i in range(1,8) )
        cache.set("__namespace_%s__" % (namespace,), key_prefix, 900)
    return '%s_%s_%s' % (key_prefix, namespace, key)

def ns_flush(namespace):
    """Flushes all keys in the specified namespace."""
    if not isinstance(namespace, (unicode, str)):
        namespace = '_'.join(str(a) for a in namespace)
    cache.delete("__namespace_%s__" % (namespace,))
